<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" size="small" :inline="true" v-show="showSearch"
             label-width="100px">
      <el-form-item label="任务名称" prop="nodeName">
        <el-input
          v-model="queryParams.nodeName"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="流程状态" prop="flowStatus">
        <el-select v-model="queryParams.flowStatus" placeholder="请选择流程状态" clearable>
          <el-option
            v-for="dict in flow_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          clearable size="small"
          v-model="queryParams.createTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="instanceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" fixed/>
      <el-table-column label="id" width="100" align="center" prop="id" :show-overflow-tooltip="true"/>
      <el-table-column label="流程名称" align="center" prop="flowName" :show-overflow-tooltip="true"/>
      <el-table-column label="任务名称" width="200" align="center" prop="nodeName" :show-overflow-tooltip="true"/>
      <el-table-column label="审批人" align="center" prop="approver" :show-overflow-tooltip="true"/>
      <el-table-column label="流程状态" align="center" prop="flowStatus" :show-overflow-tooltip="true">
        <template #default="{ row }">
          <dict-tag :options="flow_status" :value="row.flowStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="激活状态" align="center" prop="activityStatus" width="140" sortable="custom"
                       :show-overflow-tooltip="true">
        <template #default="{ row }">
          <!--          <dict-tag :options="activity_status" :value="row.activityStatus"/>-->
          <el-tag :type="row.activityStatus === 0 ? 'success' : 'danger'">
            {{ row.activityStatus == '1' ? "激活" : "挂起" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160" :show-overflow-tooltip="true">
        <template #default="{ row }">
          <span>{{ parseTime(row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="260" fixed="right" class-name="small-padding fixed-width">
        <template #default="{ row }">
          <el-button
            size="small"
            type="text"
            @click="handle(row, false)"
            v-hasPermi="['flow:execute:handle']"
          >办理
          </el-button>
          <el-button
            size="small"
            type="text"
            @click="toFlowImage(row.instanceId)"
          >流程图
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <component
      :is="approveComponent"
      v-model="businessId"
      :type="'0'"
      :taskId="taskId"
      :showAnyNode="showAnyNode"
      :formId="formPath"
      @refresh="getList"
    />

    <el-dialog title="流程图" width="70%" v-model="flowChart" append-to-body>
      <WarmChart :insId="insId"/>
    </el-dialog>

    <el-dialog :title="auditTitle" v-model="audit" width="600px" append-to-body>
      <el-form ref="form" :model="auditForm" label-width="110px">
        <el-form-item label="审批详细数据">
          <el-card style="width: 100%">
            <template #header>
              <h1>{{JSON.parse(auditForm.variable).businessData.title}}</h1>
            </template>
            <div v-for="(value,key) in JSON.parse(auditForm.variable).businessData" :key="key">
              <div v-if="key!=='title'">
                <strong>{{key}}</strong>：<span class="justify-start mb-6 text-gray-800 ">{{value}}</span>
              </div>
            </div>
          </el-card>
        </el-form-item>
        <el-form-item label="审批意见" prop="message">
          <el-input v-model="auditForm.message" type="textarea" placeholder="请输入审批意见"
                    :autosize="{ minRows: 4, maxRows: 4 }"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleBtn('PASS')">审批通过</el-button>
        <el-button @click="handleBtn('REJECT')">退回</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, markRaw, shallowRef} from 'vue';
import {ElMessageBox} from 'element-plus';
import * as api from "@/api/flow/execute";
import WarmChart from "@/views/flow/definition/warm_chart.vue";
import {parseTime} from '@/utils/ruoyi';
import {auditWorkFlow} from '@/api/workflow/workflow'

const {proxy} = getCurrentInstance();
// 字典数据
const {flow_status} = proxy.useDict("flow_status");

// 响应式数据
const loading = ref(true);
const flowChart = ref(false);
const insId = ref(null);
const instanceList = ref([]);
const total = ref(0);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const approveComponent = shallowRef(null);
const taskId = ref("");
const businessId = ref("");
const formPath = ref("");
const showAnyNode = ref(false);
const queryFormRef = ref();
const dialogTitle = ref("");
const form = reactive({
  assigneePermission: []
});
const audit = ref(false);
const auditTitle = ref('');

const auditForm = ref({});

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  nodeName: null,
  flowStatus: null,
  approver: null,
  createTime: null,
});

// 生命周期钩子
onMounted(() => {
  getList();
});

// 方法定义
async function getList() {
  loading.value = true;
  try {
    const response = await api.toDoPage(queryParams);
    instanceList.value = response.rows;
    total.value = response.total;
  } catch (error) {
    console.error("获取任务列表失败:", error);
  } finally {
    loading.value = false;
  }
}

function handleQuery() {
  queryParams.pageNum = 1;
  getList();
}

function resetQuery() {
  Object.assign(queryParams, {
    nodeName: null,
    flowStatus: null,
    approver: null,
    createTime: null,
  });
  handleQuery();
}

function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

async function handle(row, anyNode) {
  taskId.value = row.id;
  audit.value = !audit.value
  auditTitle.value=row.flowName
  auditForm.value = row
}

function toFlowImage(instanceId) {
  insId.value = instanceId;
  flowChart.value = true;
}

async function handleUserSelect(checkedItemList) {
  form.assigneePermission = checkedItemList.map(e => e.userId);

  const operatorTypeObj = {
    "转办": "2",
    "加签": "6",
    "委派": "3",
    "减签": "7"
  };

  try {
    await api.interactiveType(
      taskId.value,
      form.assigneePermission.join(','),
      operatorTypeObj[dialogTitle.value]
    );
    ElMessageBox.alert(`${dialogTitle.value}成功`, '操作成功', {type: 'success'});
    getList();
  } catch (error) {
    console.error(`${dialogTitle.value}失败:`, error);
    ElMessageBox.alert(`${dialogTitle.value}失败: ${error.message}`, '操作失败', {type: 'error'});
  }
}

function handleBtn(skipType) {
  console.log(auditForm,"==========")
  auditWorkFlow(auditForm.value, this.taskId, skipType, auditForm.value.message, this.nodeCode, this.flowStatus).then(response => {
    proxy.$modal.msgSuccess("新增成功");
    audit.value = false
    getList();
  });
  // audit.value = false
  // getList();
}
</script>

<style scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.el-form {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.el-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.el-table::before {
  display: none;
}

.el-button--text {
  padding: 5px;
  font-weight: 500;
}

.operation-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.el-dialog {
  border-radius: 10px;
  overflow: hidden;
}

.el-dialog__header {
  background-color: #f5f7fa;
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

.el-dialog__title {
  font-weight: 600;
  color: #303133;
}

.el-dialog__body {
  padding: 20px;
}
</style>
